package org.xukai.common.thread;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URI;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
public class HttpMethodManager {

    private final Logger logger = Logger.getLogger(this.getClass());

    @Resource
    private HttpClientManager httpClientManager;


    public String getPostMethod(String url, List<NameValuePair> params) {
        HttpResponse httpResponse = null;
        HttpEntity entity = null;
        String resstr = null;
        try {
            HttpPost post = new HttpPost(url);
            HttpClient httpClient = httpClientManager.getHttpClient();
            if (params != null && params.size() > 0) {
                post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            }
            httpResponse = httpClient.execute(post);
            int code = httpResponse.getStatusLine().getStatusCode();
            if (code != 200) {
                logger.error("http status error code = " + code + ",url=" + url);
                post.abort();
                return null;
            }
            entity = httpResponse.getEntity();
            if (entity != null) {
                resstr = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            // 处理异常
            logger.error("http请求异常url=" + url, e);
        }
        try {
            if (httpResponse != null) {
                EntityUtils.consume(entity); // 会自动释放连接
            }
        } catch (Exception e) {
            // 处理异常
            logger.error("http请求异常url=" + url, e);
        }
        return resstr;
    }

    public String getPostMethodWithCookie(String url, List<NameValuePair> params, String cookieStr) {
        HttpResponse httpResponse = null;
        HttpEntity entity = null;
        String resstr = null;
        try {
            HttpPost post = new HttpPost(url);
            HttpClient httpClient = httpClientManager.getHttpClient();
            if (params != null && params.size() > 0) {
                post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            }
            post.addHeader("Cookie", cookieStr);
            httpResponse = httpClient.execute(post);
            int code = httpResponse.getStatusLine().getStatusCode();
            if (code != 200) {
                logger.error("http status error code = " + code + ",url=" + url);
                post.abort();
                return null;
            }
            entity = httpResponse.getEntity();
            if (entity != null) {
                resstr = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            // 处理异常
            logger.error("http请求异常url=" + url, e);
        }
        try {
            if (httpResponse != null) {
                EntityUtils.consume(entity); // 会自动释放连接
            }
        } catch (Exception e) {
            // 处理异常
            logger.error("http请求异常url=" + url, e);
        }
        return resstr;
    }


    public String getGetMethod(String url, Map<String, Object> param) {
        StringBuilder paramBuilder = new StringBuilder();
        if (param != null && param.size() > 0) {
            for (Iterator<String> iter = param.keySet().iterator(); iter.hasNext();) {
                String key = iter.next();
                Object value = param.get(key);
                if (paramBuilder.length() == 0) {
                    paramBuilder.append("?");
                } else {
                    paramBuilder.append("&");
                }
                paramBuilder.append(key).append("=").append(value);
            }
        }
        return getGetMethod(url + paramBuilder.toString());
    }


    public String getGetMethod(String url) {
        HttpResponse httpResponse = null;
        HttpEntity entity = null;
        String resstr = null;
        try {
            url = url.replaceAll(" ", "%20");
            HttpGet get = new HttpGet(url);
            HttpClient httpClient = httpClientManager.getHttpClient();
            httpResponse = httpClient.execute(get);
            int code = httpResponse.getStatusLine().getStatusCode();
            if (code != 200) {
                logger.error("http status error code = " + code + ",url=" + url);
                get.abort();
                return null;
            }
            entity = httpResponse.getEntity();
            if (entity != null) {
                resstr = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            // 处理异常
            logger.error("http请求异常url=" + url, e);
        }
        try {
            if (httpResponse != null) {
                EntityUtils.consume(entity); // 会自动释放连接
            }
        } catch (Exception e) {
            // 处理异常
            logger.error("http请求异常url=" + url, e);
        }
        return resstr;
    }


    public String getGetMethod(URI uri) {
        HttpResponse httpResponse = null;
        HttpEntity entity = null;
        String resstr = null;
        try {
            HttpGet get = new HttpGet(uri);
            HttpClient httpClient = httpClientManager.getHttpClient();
            httpResponse = httpClient.execute(get);
            int code = httpResponse.getStatusLine().getStatusCode();
            if (code != 200) {
                logger.error("http status error code = " + code + ",url=" + uri.toString());
                get.abort();
                return null;
            }
            entity = httpResponse.getEntity();
            if (entity != null) {
                resstr = EntityUtils.toString(entity);
            }
        } catch (Exception e) {
            // 处理异常
            logger.error("http请求异常url=" + uri.toString(), e);
        }
        try {
            if (httpResponse != null) {
                EntityUtils.consume(entity); // 会自动释放连接
            }
        } catch (Exception e) {
            // 处理异常
            logger.error("http请求异常url=" + uri.toString(), e);
        }
        return resstr;
    }

}
